/**
 * @author Hemant
 * WebReportGenerator.java
 * This class generates HTML pages from webreport id already in database.
 */

/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  guireportgenerator;

import java.awt.FileDialog;
import java.awt.Frame;
import java.io.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
//import java.util.Iterator;
import java.util.LinkedList;

import logger.PoolLogger;

import utility.Input;
import utility.CapitalChar;
import utility.Replace;
import database.RecordSearch;
import dbmanager.*;
import guifilegenerator.*;

public class WebReportGenerator
{
    String report,path,datapath,line,reportID;
    GetIdName get;
    RandomAccessFile raf;
    StringBuffer buffer;
    Hashtable<Object,LinkedList<Object>> ObjProp;
    Hashtable<Object, Object> ParamHash;
    LinkedList<Object> proplist;
    File newfile;
    String fileformat,header="";
    PoolLogger logger;
    /**
     * Constructor 
     * @param ReportId Master id of report.
     * @param param Parameter for report. 
     * @param db DBManager object.
     */
    public WebReportGenerator(String ReportId,Hashtable<Object, Object> hash, String fileformat) 
    {
    	get = new GetIdName();
    	
    	logger = (PoolLogger)PoolLogger.getLogger(this.getClass().toString());
    	
    	this.fileformat = fileformat;
        // report name is extracted.
        this.report = get.getItem(ReportId).toLowerCase();
        // report id is set.
        this.reportID = ReportId;
        // path for webreports text files from which tet files to be read
        this.path = Input.WEB_REPORTS_FILES+this.report+Input.FILRFORMAT;
        
        if(fileformat.equalsIgnoreCase(".html"))
        {
        	// path for new HTML file        
        	newfile = new File(Input.LOCATION+this.report+this.fileformat);
        }
        else
        {
        	// path for new XML file        
        	newfile = new File(Input.WEB_REPORTS_FILES+this.report+this.fileformat);
        }
        
        buffer = new StringBuffer();
        
        this.ParamHash = hash;
    }
    
    
    public void setHeader(String header)
    {
    	this.header = header;    	
    }
    /**
     * This method checks if webreport text file is exists or not. If not it
     * calls GenerateTextFile class to create text file for that HTML object
     * If text file already exists then it calls FileObjectsfinder class which
     * gives a hashtable contaning objects and its properties. It starts with the report
     * object and recursively it calls its properties and generate HTML code for them.
     * @return String contaning HTML code sequence for specific webreport.
     */
    public String generateWebReport()
    {
    	try
        {
            raf = new RandomAccessFile(path,"r");
        }
        catch(FileNotFoundException e)
        {
            System.out.println("The report file does not exists so let's create it");
            logger.info("The report file does not exists so let's create it");
            // Calls GenerateTextFile class to generate text file.
            GenerateTextFile gen = new GenerateTextFile(reportID,this.fileformat);
            if(gen.generateFile())
            {
	            try
	            {
	                raf = new RandomAccessFile(path,"r");
	            }
	            catch(FileNotFoundException e1)
	            {
	            	e1.printStackTrace();
	            }
            }
        }
        catch(Exception e)
        {
        	e.printStackTrace();
        }
        
        // Call FileObjectsfinder to generate hashtable
        FileObjectsfinder find = new FileObjectsfinder(path);
        ObjProp = find.getobject_Properties();
        System.out.println("Let's fetch properties of object "+report);
        // Get property list for report object
        proplist = ObjProp.get(report.toLowerCase());
        
        StringBuffer sbr = new StringBuffer();
        sbr.append("");    
        
        // Get size of propertylist of report object
        int size = proplist.size();
        // Create reference variable of type HTMLInterface
        guiproperty.HTMLInterface obj = null;
        StringBuffer tempbuffer = new StringBuffer();
        tempbuffer.append("");
        StringBuffer attbuffer = new StringBuffer();
        attbuffer.append("");
        String tag = "";
        //The flag variable is set when there is a property "type"
        boolean flag = false;
        // Create ref variable of type Class
        Class myclass = null;
        
        // Iterate over propertylist of report object.
        for(int i=0;i<size;i++)
        {	
        	// Copy the first element from propertylist
            String element = (String)proplist.element();
            System.out.println("The element "+element+" is now removed");
            // Remove copied element from propertylist
            proplist.remove();
            // Split copied element on Special char
            String [] property_arr = element.split(Input.SEPARATOR);
            
            String property = property_arr[0].trim();
            System.out.println("The property is "+property);
            String property_value = property_arr[1].trim();
            System.out.println("The property val is "+property_value);
            //String property_order  = property_arr[2].trim();
            
            try 
            {	            	
                // if property is webreport call the WebReportGenerator class 
                if(property.equalsIgnoreCase("webreport"))
                {
                    WebReportGenerator web = new WebReportGenerator(property_value,ParamHash,this.fileformat);
                    tempbuffer.append(web.generateWebReport());
                }
                else if(property.equalsIgnoreCase("header"))
                {
                	this.setHeader(property_value);
                }
                else
                {
                	// Set classname with property name.
                    String classname = CapitalChar.makeFirstCharCapital(property);
                    System.out.println("The class name is "+classname);
                    
                    // Create Class type object using forName() method and bind it to Calss type variable
                    myclass = Class.forName("guiproperty."+classname);
                    
                    try
                    {
                    	// Create instance of Class type variable and bind it to HTMLInterface type object.
                        obj = (guiproperty.HTMLInterface)myclass.newInstance();
                    }
                    catch (InstantiationException e)
                    {
                        e.printStackTrace();
                    }
                    catch (IllegalAccessException e)
                    {
                        e.printStackTrace();
                    }
                    
                    // Set all the properties for HTMLInterface object
                    //obj.setDatabase();
                    obj.setGetIdName(get);
                    obj.setObjectName(property_value);
                    obj.setObjPropertyList(ObjProp);
                    obj.setParamHash(ParamHash);
                    obj.setLine(line);
                    obj.setReport(report);
                    obj.setTag(tag);
                    
                    // if property is "attribute"
                    if(classname.equalsIgnoreCase("attribute"))
                    {
                    	attbuffer.append(obj.getHTMLCode());
                    }
                    else
                    {
                    	tempbuffer.append(obj.getHTMLCode());
                    }
                }                				
            }
            catch (ClassNotFoundException e) 
            {
                //e.printStackTrace();
                System.out.println("This is not a class "+property);
                
                if(property.equalsIgnoreCase("type"))
                {
                        tag = property_value;
                        flag = true; 
                }                
            }            
        }
        
        if(flag && !tag.equalsIgnoreCase("webreport"))
        {
            sbr.append("<"+tag+" "+attbuffer+">"+tempbuffer.toString()+"</"+tag+">");
        }
        else
        {
            sbr.append(tempbuffer.toString());
        }
        
        System.out.println("The sbr in generatewebReport is "+sbr.toString());
        logger.info("The sbr in generatewebReport is "+sbr.toString());
        return sbr.toString();
    }
    
    /**
     * This method call generateWebReport() method. Then creates a file with 
     * the HTML string 
     * @return HTML code
     */
    public String getData()
    {
    	String result = this.generateWebReport();
    	
    	if(this.fileformat.equalsIgnoreCase(".html"))
    		result = result.replace("\"", "\'");
    	
    	result = Replace.Replace(result, Input.WEBREPLACER,"\n" );
    	result = this.header + result;
        FileWriter fw = null;
        
        Hashtable<Object, Object> condition = new Hashtable<Object, Object>();
		condition.put("mid",this.reportID);
		condition.put("pid",get.getId("pagetype"));
		condition.put("td", "null");
		RecordSearch rec = new RecordSearch();
		rec.setConditionMap(condition);
		ResultSet rs = rec.getResultSet();
		String pagetype = "static";
		
		try 
		{
			while(rs.next())
			{
				pagetype = get.getItem(rs.getString("PV"));
				if(pagetype.equalsIgnoreCase("no$"))
					pagetype = rs.getString("VT");
			}
			rs.close();			
				
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
		try
		{
			if (pagetype.equalsIgnoreCase("static")) 
			{
				if (newfile.createNewFile() == true) {
					System.out.println("File Created" + newfile);
					fw = new FileWriter(newfile);
					fw.write(result);
			    	fw.flush();
				} else {
					System.out.println("File Already Exists " + newfile
							+ " Has to be deleted first");
					if (newfile.delete() == true) {
						System.out.println("File deleted " + newfile);
						if (newfile.createNewFile() == true) 
						{
							System.out.println("File Created" + newfile);
							fw = new FileWriter(newfile);
							fw.write(result);
					    	fw.flush();
						}
					} else {
						System.out.println("File not deleted " + newfile);
					}
				}
			}
			else if(pagetype.equalsIgnoreCase("dynamic"))
			{
				fw = null;
			}
		}
		catch (Exception e) 
		{
		    e.printStackTrace();
		}
		finally
		{
		    try 
		    {
		        fw = null;
		    }
		    catch (Exception e)
		    {
		       e.printStackTrace();
		    }
		}
		
        return result;
    }
    
    public static void main(String[] args) 
    {
        System.out.println("I'm in main");
        GetIdName get = new GetIdName();
        
        Hashtable<Object, Object> hash = new Hashtable<Object, Object>();
        ResultSet rsTran = DBManager.getSelect("select * from transaction where id=216");
		
		hash.put("po.id", 216);
		
		try
		{
			/*hash.put("po.buyer", "aaa");
			hash.put("po.seller", "aac");
			hash.put("po.delivery_date", "2008-02-12 00:00:00");
			hash.put("PO.item", "ada");
			hash.put("name", "masterstorage");
			hash.put("type", "storage");
			hash.put("path", "textfiles//MasterReport");*/
			
			/*hash.put("name", "ashirwaad Aata");
			hash.put("grade", "A");
			hash.put("item.itemcode", "a001");*/
			hash.put("type", "master");
			//hash.put("mastername", "nirma det soap");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
        //WebReportGenerator bill  = new WebReportGenerator("BillReport","212");
        //WebReportGenerator bill  = new WebReportGenerator("master","");
        //WebReportGenerator bill  = new WebReportGenerator("transaction","");
        //WebReportGenerator bill  = new WebReportGenerator("Item","");
        //WebReportGenerator bill  = new WebReportGenerator("Employee","");
        //WebReportGenerator bill  = new WebReportGenerator("Retailer","");
        //WebReportGenerator bill  = new WebReportGenerator("User","");
        //WebReportGenerator bill  = new WebReportGenerator("NewEmployee","");
        //WebReportGenerator bill  = new WebReportGenerator("NewItem","");
        //WebReportGenerator bill  = new WebReportGenerator("NewRetailer","");
        //WebReportGenerator bill  = new WebReportGenerator("MyForm","");
        //WebReportGenerator webreport  = new WebReportGenerator("16947",hash,db);
		//WebReportGenerator webreport  = new WebReportGenerator("21338",hash,db);
		WebReportGenerator webreport  = new WebReportGenerator("12863",new Hashtable<Object, Object>(),".xsql");
        System.out.println(webreport.getData());
    }
}
